package cn.songtx.iot.controller.Device;

import cn.songtx.iot.pojo.DeviceEm;
import cn.songtx.iot.pojo.Result;
import cn.songtx.iot.service.IDeviceEmService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("/EM")
@RequiredArgsConstructor
public class emController {

    private final IDeviceEmService deviceEmService;

    /**
     * 用get方法,Params传入mac,查询最后一组数据
     * 使用条件构造器,构造根据id倒序排列,匹配mac,最后一条
     *
     * @param mac 按照mac地址查询
     * @return 统一的Result
     */
    @RequestMapping(value = "/getOne", method = RequestMethod.GET)
    public Result emGetOne(String mac) {
        LambdaQueryWrapper<DeviceEm> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.orderByDesc(DeviceEm::getId)
                .eq(DeviceEm::getMac, mac)
                .last("limit 1");
        DeviceEm one = deviceEmService.getOne(lambdaQueryWrapper);
        return Result.success(one);
    }

    /**
     * 带mac条件的分页查询
     * 使用分页插件完成分页功能 mybatisplus.extension.plugins.pagination.Page;
     * POST请求体中携带分页对象{"current":页码,"size":每页几条数据},用map接收
     *
     * @param mac     设备的mac地址
     * @param current 页码
     * @param size    第几页
     * @return 统一的Result
     */
    @RequestMapping(value = "/pages", method = RequestMethod.GET)
    public Result emPages(String mac, Long current, Long size) {
        // 1.创建分页对象,并传入分页参数
        IPage<DeviceEm> iPage = new Page<>(current, size);
        // 2.查询条件,mac
        LambdaQueryWrapper<DeviceEm> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.orderByDesc(DeviceEm::getId).eq(DeviceEm::getMac, mac);
        // 3.调用分页方法,返回分页对象
        IPage<DeviceEm> page = deviceEmService.page(iPage, lambdaQueryWrapper);
        return Result.success(page);
    }

    /**
     * 查询某个月份的峰谷电量
     * 返回的格式为 Map<String, float[]>
     *
     * @param year  年份
     * @param month 月份
     * @return 统一的Result
     */
    @RequestMapping(value = "/getPeakValleyByMonth", method = RequestMethod.GET)
    public Result emPeakValleyElectricByMonth(String mac, String year, String month) {
        Map<String, float[]> map = deviceEmService.selectPeakValleyElectricByMonth(mac, year, month);
        return Result.success(map);
    }
}
